package com.atguigu.tingshu.search.runners;

import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.search.service.impl.ItemServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.redisson.api.RBloomFilter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * Description:  主要完成对分布式布隆过滤器数据的初始化
 */
//@Component
@Slf4j
public class DistroBloomFilterInitRunner implements ApplicationRunner, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args){
        // 1.从Spring容器中获取分布式布隆过滤器
        RBloomFilter rBloomFilter = applicationContext.getBean("rBloomFilter", RBloomFilter.class);

        // 2.从MySQL找到要同步给布隆过滤器的数据
        AlbumInfoFeignClient albumInfoFeignClient = applicationContext.getBean("albumInfoFeignClient", AlbumInfoFeignClient.class);
        List<Long> albumIds = albumInfoFeignClient.getAllAlbumInfoIds().getData();

        // 3.将数据放到布隆过滤器中

        if (!CollectionUtils.isEmpty(albumIds)) {
            for (Long albumId : albumIds) {
                rBloomFilter.add(albumId);
            }
            log.info("分布式布隆过滤器数据初始化完毕，且元素个数为：{}", rBloomFilter.count());
        }
    }


    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
